package com.zxr.web.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zxr.common.core.controller.BaseController;
import com.zxr.common.core.domain.AjaxResult;
import com.zxr.common.utils.*;
import com.zxr.common.utils.http.HttpUtils;
import com.zxr.framework.jwt.utils.JwtUtils;
import com.zxr.system.domain.Member;
import com.zxr.system.domain.PhoneInfo;
import com.zxr.system.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/wx")
public class WxLoginController extends BaseController
{


    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Value("${wx.loginUrl}")
    private String wxLoginUrl;

    // 获取access_token
    private String ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?";

    // 获取号码
    private String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?";

    @Autowired
    private IMemberService memberService;

    @PostMapping("/autoLogin")
    @ResponseBody
    public String autoLogin(@RequestBody Map<String, String> req) {
        String code = req.get("code");
        appId = "xx";
        appSecret = "xxxx";
        wxLoginUrl="https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code
                + "&grant_type=authorization_code";
        String result = HttpUtils.sendWXGet(wxLoginUrl, param);
        JSONObject jsonpObject = JSONObject.parseObject(result);
        String openid = jsonpObject.getString("openid");
        Member memberVO =  memberService.selectMemberByOpenId(openid);
        if (memberVO == null) {
            String accessToken = this.getAccessToken(appId,appSecret);
            String honeNumber = this.getuserphonenumber(accessToken,"用户同意的code");
            Member member1 =new Member();

//            member1.setAvatar(11);
//            member1.setNickName();
            member1.setOpenId(openid);
            member1.setPhone(honeNumber);
//            member1.setUnionId();
            memberService.insertMember(member1);
        }
        return JwtUtils.createToken(openid,appSecret);
    }
    private String getuserphonenumber(String accessToken, String code) {
        String honeNumber = "";
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("code", code);
            String  param = JSON.toJSONString(map);
            String result = HttpUtils.sendlogWXPost(PHONE_URL+"access_token="+accessToken, param);
            JSONObject jsonpObject = JSONObject.parseObject(result);
            PhoneInfo phoneInfo = (PhoneInfo)jsonpObject.get("phone_info");
            honeNumber = phoneInfo.getPhoneNumber();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return honeNumber;
    }
    private String getAccessToken(String APP_ID, String SECRET) {
        String accessToken = null;
        try {
            String token = ExpireDataUtil.get("access_token");
            if (null == token) {
                String param = MessageFormat.format("grant_type=client_credential&appid={0}&secret={1}", APP_ID, SECRET);
                String result = HttpUtils.sendPost(ACCESS_TOKEN_URL, param);
                JSONObject jsonpObject = JSONObject.parseObject(result);
                accessToken = jsonpObject.getString("access_token");
                Integer expiresTime = (jsonpObject.getInteger("expires_in") - 100) * 1000;
                long redisExpireTime = System.currentTimeMillis() + expiresTime;
                ExpireDataUtil.add("access_token",accessToken,redisExpireTime/1000);
            } else {
                accessToken = token;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return accessToken;
    }
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult wxLogin(@RequestBody Map<String, String> req) {
//        String code = req.get("code");
//
//        String url = wxLoginUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
//
//
//
//        // 解析微信服务器的响应
//        String responseBody = HttpUtils.sendGet(url);
//        //提取openid和session_key
//        Map<String, String> wxResponse = parseWxResponse(responseBody);
//        String openid = wxResponse.get("openid");
//        String session_key = wxResponse.get("session_key");
        String openid = "qwe123456";
        // 检查数据库中是否已经有一个与这个openid关联的用户
        Member member = memberService.selectMemberByOpenId(openid);
        if(member!=null){
            return AjaxResult.success("登录成功",JwtUtils.createToken(openid,appSecret));
        }else{
            Member member1 =new Member();
            member1.setAvatar("1111");
            member1.setNickName("zhangsan");
            member1.setOpenId("qwe123456");
            member1.setUnionId("qwe123456");
            member1.setPhone("13811781991");
             memberService.insertMember(member1);
        }

        return AjaxResult.success("登录成功",JwtUtils.createToken(openid,appSecret));
    }

    private Map<String, String> parseWxResponse(String responseBody) {
        Map<String, String> wxResponse = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(responseBody);
        wxResponse.put("openid", jsonObject.getString("openid"));
        wxResponse.put("session_key", jsonObject.getString("session_key"));
        return wxResponse;
    }

}
